﻿using BLL;
using DAL;
using Models.OrderMealManageSubSystem;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.SessionState;
using WeChat.HTTP_Helper;

namespace WeChat.OrderMealManageSubSystem
{
    /// <summary>
    /// OrderParameterSetting 的摘要说明
    /// </summary>
    public class OrderParameterSetting : IHttpHandler, IRequiresSessionState
    {

        private string _operatorName;
        private string _openid;
        private object Order_payment = new object();

        public void ProcessRequest(HttpContext context)
        {
            string functionName = context.Request.Form["functionName"];
            _operatorName = context.Session["userName"]?.ToString() ?? "";
            _openid = context.Session["openid"] == null ? "" : context.Session["openid"].ToString();
            ApplicationLog.Write("GetOrderParameterSetting获取到openid值：" + _openid);
            string returnStr = "";
            switch (functionName)
            {
                case "GetOrderParameterSetting":
                    returnStr = GetOrderParameterSetting(context);
                    break;
                case "SetOrderParameterSetting":
                    returnStr = SetOrderParameterSetting(context);
                    break;
            }
            context.Response.ContentType = "text/plain";
            context.Response.Write(returnStr);
        }

        private string GetOrderParameterSetting(HttpContext context)
        {
            JObject result = new JObject();
            DataSet resultSet = OrderParameterSettingBLL.GetOrderParameterSetting(_openid);

            DataRow parameterSetting = resultSet.Tables[0].Rows[0];

            DataRowCollection orderDates = resultSet.Tables[1].Rows;

            DataRow parameterRyxx = resultSet.Tables[2].Rows[0];

            DataRow parameterthisMonth = resultSet.Tables[3].Rows[0];

            DataRow parameternextMonth = resultSet.Tables[4].Rows[0];

            List<string> orderDate = new List<string>();

            foreach (DataRow row in orderDates)
            {
                orderDate.Add(row["orderDate"].ToString());
            }

            GetOrderParameterSettingDataModel data = new GetOrderParameterSettingDataModel
            {
                breakfastAmount = Convert.ToDouble(parameterSetting["breakfastAmount"]),
                lunchAmount = Convert.ToDouble(parameterSetting["lunchAmount"]),
                dinnerAmount = Convert.ToDouble(parameterSetting["dinnerAmount"]),
                orderSwitch = Convert.ToInt32(parameterSetting["orderSwitch"]),
                OrderDate = orderDate,
                rfye = Convert.ToDouble(parameterRyxx["rfye"]),
                grye = Convert.ToDouble(parameterRyxx["grye"]),
                btye = Convert.ToDouble(parameterRyxx["btye"]),
                klb = parameterRyxx["klb"].ToString(),
                thisMonthCount = Convert.ToInt32(parameterthisMonth["thisMonthCount"]),
                nextMonthCount = Convert.ToInt32(parameternextMonth["nextMonthCount"])
            };

            var settings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };

            result.Add("data", JsonConvert.SerializeObject(data, Formatting.None, settings));

            return result.ToString();
        }

        private string SetOrderParameterSetting(HttpContext context)
        {

            //string jsonString = "[{\"date\":\"2025-04-18\",\"foodTime\":\"dinner\",\"money\":10},{\"date\":\"2025-04-19\",\"foodTime\":\"breakfast\",\"money\":2.9},{\"date\":\"2025-04-19\",\"foodTime\":\"lunch\",\"money\":9}]";
            //var jsonssss = jsonString;

            //var Pagelist = new { aomunt = 109.5, orderList = jsonssss };
            //var jsonDatas = JsonConvert.SerializeObject(Pagelist);
            var ryid = OrderParameterSettingBLL.GetRyid(_openid);
            var oederIds = OrderingOrderNumber() + ryid;
            JObject result = new JObject();
            var json = context.Request["data"];
            Dictionary<string, string> arguments = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
            var amount = arguments["amount"].ToString();
            var orderList = arguments["orderList"].ToString();

            List<GetOrderParameterSettingModel> lists = new List<GetOrderParameterSettingModel>();
            lists = JsonConvert.DeserializeObject<List<GetOrderParameterSettingModel>>(orderList);
            var foodNum = 0;
            foreach (var item in lists)
            {

                var foodTime = item.foodTime;
                if (foodTime == "breakfast")
                {
                    foodTime = "早餐";
                    foodNum = 1;
                }
                else if (foodTime == "lunch")
                {
                    foodTime = "午餐";
                    foodNum = 2;
                }
                else if (foodTime == "dinner")
                {
                    foodTime = "晚餐";
                    foodNum = 3;
                }
                //var date_ = item.date;
                //var money = item.money;
                //var OrderId = OrderingOrderNumber() + ryid;

                SetOrderParameterSettingModel data = new SetOrderParameterSettingModel
                {
                    date = item.date,
                    money = Convert.ToDouble(item.money),
                    OrderId = OrderingOrderNumber()+ foodNum + ryid,
                    foodTime = foodTime,
                    ryid = ryid,
                    TotalOrderId = oederIds
                };


                bool updateResults = OrderParameterSettingBLL.SetOrderParameterSetting(data);

            }
            //var ss = arguments.aomunt;
            //var list = arguments.orderList;

            int updateResult = OrderParameterSettingBLL.SetOrderParameterSettingPayAdd(ryid,Convert.ToDouble(amount), oederIds);
            if (updateResult > 0)
            {
                result.Add("result", true);
                result.Add("message", "支付成功");

                ApplicationLog.Write("包月订餐返回结果：" + updateResult + "，oederIds值：" + oederIds);
                Thread thread1 = new Thread(() =>
                {
                    lock (Order_payment)
                    {
                        Thread.Sleep(300);
                        try
                        {
                            //同步扣款
                            //获取卡号、用户编号	
                            DataTable dns = OrderParameterSettingBLL.Select_CUST_ID(oederIds);
                            string CUST_ID = dns.Rows[0]["bankcard"].ToString();//CUST_ID
                            string CARD_ID = dns.Rows[0]["rfkh"].ToString();//用户编号	
                                                                            //string ORDER_ID = GenerateOutTradeNos();//随机数生成订单号
                            string ORDER_ID = oederIds.ToString();//随机数生成订单号
                                                                  //设置机器号
                            string device_number = ConfigurationSettings.AppSettings["device_number"] == "" ? "000" : ConfigurationSettings.AppSettings["device_number"].ToString();
                            ApplicationLog.Write("获取到设置机器号：" + device_number);
                            //获取商家编号、柜台编号
                            DataTable BD = MenuReservationBLL.Get_BUSINESS_ID(device_number);
                            string BUSINESS_ID = BD.Rows[0]["MacAddress"].ToString();//商家编号	
                            string VPOS_ID = BD.Rows[0]["xlmc"].ToString();//柜台编号	
                            if (BUSINESS_ID == null || VPOS_ID == null || BUSINESS_ID == "" || VPOS_ID == "")
                            {
                                ApplicationLog.Write("商家编号为空：" + BUSINESS_ID + ",柜台编号为空:" + VPOS_ID);
                            }
                            else
                            {
                                ApplicationLog.Write("商家编号：" + BUSINESS_ID + ",柜台编号:" + VPOS_ID);
                            }

                            //同步调用接口消费
                            //获取到修改信息,进行同步
                            string CAMPUS_NAME = ConfigurationSettings.AppSettings["CAMPUS_NAME"];
                            string CAMPUS_ID = ConfigurationSettings.AppSettings["CAMPUS_ID"]; //园区ID		
                            string CORP_ID = ConfigurationSettings.AppSettings["CORP_ID"];     //合作方ID	 
                            string Sign = ConfigurationSettings.AppSettings["ccbSafeParam"];
                            string key_url = ConfigurationSettings.AppSettings["key_url"];//密钥url
                            string Request_Link = ConfigurationSettings.AppSettings["Request_Link"];//请求链接
                            Dictionary<string, string> pairs = new Dictionary<string, string>();
                            pairs.Add("CAMPUS_ID", CAMPUS_ID);
                            pairs.Add("CORP_ID", CORP_ID);
                            pairs.Add("TXCODE", "PAY005");
                            pairs.Add("BUSINESS_ID", BUSINESS_ID);//商家编号		
                            pairs.Add("VPOS_ID", VPOS_ID);//柜台编号		
                            pairs.Add("PAYMENT", amount.ToString());//支付金额		
                            pairs.Add("ACTUAL_PAYMENT", amount.ToString());//实际支付金额		
                            pairs.Add("OFFLINE", "0");//联机支付	
                            pairs.Add("CARD_ID", CARD_ID);//卡号	
                            pairs.Add("CUST_ID", CUST_ID);//用户编号	
                            pairs.Add("ORDER_ID", ORDER_ID);//订单编号	
                            string Signparam = GetSignContent01(pairs);
                            ApplicationLog.Write("获取到参数：" + Signparam);
                            var context01 = new { key = Sign, data = Signparam };
                            string data = JsonConvert.SerializeObject(context01);
                            ApplicationLog.Write("token_data:" + data);
                            string ccbSafeParams = WebapiHelper.PostWebRequest(key_url, data, "", Encoding.GetEncoding("UTF-8"));
                            Dictionary<object, object> jspay_info_keys = JsonConvert.DeserializeObject<Dictionary<object, object>>(ccbSafeParams);
                            //  ApplicationLog.Write("jspay_info_key:" + jspay_info_keys);
                            string ccbSafeParam = jspay_info_keys["data"].ToString();
                            ApplicationLog.Write("获取到加密密钥：" + ccbSafeParam);

                            Dictionary<string, string> pairs01 = new Dictionary<string, string>();
                            pairs01.Add("CCB_IBSVersion", "V6");
                            pairs01.Add("PT_STYLE", "8");
                            pairs01.Add("PT_LANGUAGE", "CN");
                            pairs01.Add("CAMPUS_ID", CAMPUS_ID);
                            pairs01.Add("CORP_ID", CORP_ID);
                            pairs01.Add("TXCODE", "PAY005");
                            pairs01.Add("BUSINESS_ID", BUSINESS_ID);//商家编号		
                            pairs01.Add("VPOS_ID", VPOS_ID);//柜台编号		
                            pairs01.Add("PAYMENT", amount.ToString());//支付金额		
                            pairs01.Add("ACTUAL_PAYMENT", amount.ToString());//实际支付金额		
                            pairs01.Add("OFFLINE", "0");//联机支付	
                            pairs01.Add("CARD_ID", CARD_ID);//卡号	
                            pairs01.Add("CUST_ID", CUST_ID);//用户编号	
                            pairs01.Add("ORDER_ID", ORDER_ID);//订单编号	
                            pairs01.Add("ccbSafeParam", ccbSafeParam);

                            string context02 = GetSignContent01(pairs01);
                            ApplicationLog.Write("获取到用户信息请求参数：" + context02);
                            //测试地址：http://121.40.54.232:8090/CCBIS/B2CMainPlat_00_ZHST
                            //生产环境：https://dining.icenter.ccb.com/CCBIS/B2CMainPlat_00_ZHST
                            string Response = WebapiHelper.PostWebRequest(Request_Link + context02, "", "", Encoding.GetEncoding("UTF-8"));
                            //获取回调返回值
                            Dictionary<object, object> jspay_info_key = JsonConvert.DeserializeObject<Dictionary<object, object>>(Response);
                            //  ApplicationLog.Write("jspay_info_key:" + jspay_info_key);
                            //响应结果Y：成功 N：失败	
                            string RESULT = jspay_info_key["RESULT"].ToString();
                            ApplicationLog.Write("RESULT:" + RESULT);
                            string PAYMENT = jspay_info_key["PAYMENT"].ToString();
                            ApplicationLog.Write("PAYMENT:" + PAYMENT);
                            string ACC_NO = jspay_info_key["ACC_NO"].ToString();
                            ApplicationLog.Write("ACC_NO:" + ACC_NO);
                            string ACC_TYPE = jspay_info_key["ACC_TYPE"].ToString();
                            ApplicationLog.Write("ACC_TYPE:" + ACC_TYPE);
                            string ACC_LIST = jspay_info_key["ACC_LIST"].ToString();
                            ApplicationLog.Write("ACC_LIST:" + ACC_LIST);

                        }
                        catch (Exception e)
                        {

                            ApplicationLog.Write("包月扣款异常信息为：" + e.Message);
                        }
                    }
                });

                thread1.Start();
                thread1.Join();
            }
            else
            {
                result.Add("result", false);
                result.Add("message", "支付失败,参数解析异常");
            }

            return result.ToString();
        }

        /**
        * 订餐订单号
            * @return 订单号
        */
        public static string OrderingOrderNumber()
        {
            var ran = new Random();
            return string.Format("{0}{1}", DateTime.Now.ToString("yyyyMMddHHmmssfff"), ran.Next(999999));
        }

        public static string GetSignContent01(IDictionary<string, string> parameters)
        {
            // 第一步：把字典按Key的字母顺序排序
            IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters);
            sortedParams = (from enty in sortedParams orderby enty.Value ascending select enty).ToDictionary(p => p.Key, p => p.Value);
            IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();

            // 第二步：把所有参数名和参数值串在一起
            StringBuilder query = new StringBuilder("");
            while (dem.MoveNext())
            {
                string key = dem.Current.Key;
                string value = dem.Current.Value;
                if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
                {
                    query.Append(key).Append("=").Append(value).Append("&");
                    //query.Append(value).Append("&");
                }
            }
            string content = query.ToString().Substring(0, query.Length - 1);

            return content;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}